package com.sebiotec.glp.limoapp;

import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.allen.library.RxHttpUtils;
import com.allen.library.interceptor.Transformer;
import com.allen.library.observer.CommonObserver;
import com.bill.module_notification.NotifyManager;
import com.google.firebase.messaging.FirebaseMessaging;
import com.sebiotec.basecommon.utils.base.BaseActivity;
import com.sebiotec.basecommon.utils.constant.SjmConstant;
import com.sebiotec.basecommon.utils.entity.event.CountEvent;
import com.sebiotec.basecommon.utils.entity.event.LoginEvent;
import com.sebiotec.basecommon.utils.language.LocalManageUtil;
import com.sebiotec.basecommon.utils.tools.ActivityTool;
import com.sebiotec.basecommon.utils.tools.SPUtils;




import com.sebiotec.driver.ui.activity.LanguageActivity;
import com.sebiotec.driver.ui.fragment.ProfileFragment;
import com.sebiotec.driver.ui.fragment.history.HisToryFragment;
import com.sebiotec.driver.ui.fragment.job.JobFragment;
import com.sebiotec.driver.ui.fragment.message.MessageFragment;

import com.sebiotec.glp.limoapp.model.MscCount;
import com.sebiotec.glp.limoapp.net.MainApiHelper;
import com.sebiotec.login.ui.activity.LoginActivity;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.next.easynavigation.view.EasyNavigationBar;
import com.xuexiang.xui.widget.toast.XToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;


@Route(path = "/App/JobMainActivity")
public class JobMainActivity extends BaseActivity {

    long exitTime = 0;
    @BindView(R.id.navigationBar)
    EasyNavigationBar navigationBar;
    private JobFragment jobFragment;

    private HisToryFragment hisToryFragment;
    private MessageFragment messageFragment;
    //未选中icon
    private int[] normalIcon = {R.drawable.menu_booking_defualt,R.drawable.menu_history_defualt,R.drawable.menu_message_defualt, R.drawable.menu_profile_defualt};
    //选中时icon
    private int[] selectIcon = {R.drawable.menu_booking_press,R.drawable.menu_history_press,R.drawable.menu_message_press, R.drawable.menu_profile_press};

    private List<Fragment> mFragments = new ArrayList<>();
    private ProfileFragment profileFragment;
    private NotifyManager notifyManager;
    private int count;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
         RxHttpUtils.cancel(SjmConstant.DRIVERNET);
    }

    @Override
    protected void initUI() {

        EventBus.getDefault().register(this);
        String[] tabText = {getString(R.string.Job), getString(R.string.history), getString(R.string.message), getString(R.string.profile)};
        jobFragment = new JobFragment();
        hisToryFragment = new HisToryFragment();
        messageFragment = new MessageFragment();
        profileFragment = new ProfileFragment();
        mFragments.add(jobFragment);
        mFragments.add(hisToryFragment);
        mFragments.add(messageFragment);
        mFragments.add(profileFragment);
        navigationBar.titleItems(tabText)
                .normalIconItems(normalIcon)
                .selectIconItems(selectIcon)
                .fragmentList(mFragments)
                .iconSize(22)     //Tab图标大小
                .tabTextSize(12)
                .fragmentManager(getSupportFragmentManager())
                .normalTextColor(getColor(R.color.l_gray))   //Tab未选中时字体颜色
                .selectTextColor(getColor(R.color.smj))   //Tab选中时字体颜色
                .canScroll(false)
                .msgPointLeft(-15)  //调节数字消息的位置msgPointLeft msgPointTop（看文档说明）
                .msgPointTop(-10)
                .build();
        if (getIntent().hasExtra("tz")) {
            Log.d("main2","进来了1");
            navigationBar.selectTab(2);
        }else if (getIntent().getBundleExtra("bundle")!=null){
            Log.d("main2","进来了2");
            navigationBar.selectTab(2);
        }else if (getIntent().getBundleExtra("language")!=null){
            navigationBar.selectTab(3);
            Log.d("main","进来了3");
            startActivity(LanguageActivity.class);
        }

    }

    @Override
    protected void initData() {

//        HashMap<String, Object> map = new HashMap<String, Object>();
//        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID, ""));
//        map.put("Token", SPUtils.get(SjmConstant.TOKEN, ""));
//        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));
//
//        MainApiHelper.geRadomApi()
//                .getMessageCount(map)
//                .compose(Transformer.<MscCount>switchSchedulers())
//                .subscribe(new CommonObserver<MscCount>() {
//                    @Override
//                    protected void onError(String errorMsg) {
//
//                    }
//
//                    @Override
//                    protected void onSuccess(MscCount s) {
//                         count = Integer.parseInt(s.getMsgCount());
//                        navigationBar.setMsgPointCount(2,count );
//
//                    }
//                });

//                        FirebaseMessaging.getInstance().subscribeToTopic("weather")
//                        .addOnCompleteListener(new OnCompleteListener<Void>() {
//                            @Override
//                            public void onComplete(@NonNull Task<Void> task) {
//
//                                if (!task.isSuccessful()) {
//
//                                }
//
//                            }
//                        });

        FirebaseInstanceId.getInstance().getInstanceId()
                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                    @Override
                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
                        if (!task.isSuccessful()) {

                            return;
                        }

                        // Get new Instance ID token
                        String token = task.getResult().getToken();

                        //提交给服务器
                        HashMap<String, Object> map2 = new HashMap<String, Object>();
                        map2.put("LoginId", SPUtils.get(SjmConstant.LOGINID, ""));
                        map2.put("Token", SPUtils.get(SjmConstant.TOKEN, ""));
                        map2.put("FCMToken", token);
                        map2.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));

                        MainApiHelper.geRadomApi()
                                .FCMToken(map2)
                                .compose(Transformer.<ResponseBody>switchSchedulers())
                                .subscribe(new CommonObserver<ResponseBody>() {
                                    @Override
                                    protected String setTag() {
                                        return SjmConstant.DRIVERNET;
                                    }
                                    @Override
                                    protected void onError(String errorMsg) {

                                    }

                                    @Override
                                    protected void onSuccess(ResponseBody s) {


                                    }
                                });

                    }
                });
//



    }
    @Override
    protected void onResume() {
        super.onResume();

        if (navigationBar.getmViewPager().getCurrentItem()!=2){
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("LoginId", SPUtils.get(SjmConstant.LOGINID, ""));
            map.put("Token", SPUtils.get(SjmConstant.TOKEN, ""));
            map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));

            MainApiHelper.geRadomApi()
                    .getMessageCount(map)
                    .compose(Transformer.<MscCount>switchSchedulers())
                    .subscribe(new CommonObserver<MscCount>() {
                        @Override
                        protected String setTag() {
                            return SjmConstant.DRIVERNET;
                        }

                        @Override
                        protected void onError(String errorMsg) {

                        }

                        @Override
                        protected void onSuccess(MscCount s) {
                            count = Integer.parseInt(s.getMsgCount());
                            navigationBar.setMsgPointCount(2,count );

                        }
                    });
        }

    }



    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.hasExtra("tz")) {
            navigationBar.selectTab(2);
        }else if (intent.getBundleExtra("bundle")!=null){

            navigationBar.selectTab(2);

        }else if (intent.getBundleExtra("language")!=null){
            navigationBar.selectTab(3);
            Log.d("main","进来了3");
            startActivity(LanguageActivity.class);
        }
    }

    @Override
    protected void setListener() {
        //这里是bottomnavigationview的点击事件

    }

    @Override
    public void onBackPressed() {

        if ((System.currentTimeMillis() - exitTime) > 2000) {
            XToast.error(this, getString(R.string.quit)).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            System.exit(0);
        }


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Jobevent(CountEvent event){

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("LoginId", SPUtils.get(SjmConstant.LOGINID, ""));
        map.put("Token", SPUtils.get(SjmConstant.TOKEN, ""));
        map.put("Lang", LocalManageUtil.getSMJSetLanguageLocales(ActivityTool.getInstance().getLastActivity()));

        MainApiHelper.geRadomApi()
                .getMessageCount(map)
                .compose(Transformer.<MscCount>switchSchedulers())
                .subscribe(new CommonObserver<MscCount>() {
                    @Override
                    protected void onError(String errorMsg) {

                    }
                    @Override
                    protected String setTag() {
                        return SjmConstant.DRIVERNET;
                    }
                    @Override
                    protected void onSuccess(MscCount s) {
                        count = Integer.parseInt(s.getMsgCount());
                        navigationBar.setMsgPointCount(2,count );

                    }
                });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void LoginOut(LoginEvent event){
        if (event.isLoginOut()){
             SPUtils.remove(SjmConstant.TOKEN);
             ActivityTool.getInstance().finishAllActivities();
             startActivity(LoginActivity.class);

        }
    }
}
